<script setup>
import { ref, onMounted } from 'vue'
import { listIndicators, listDoctors } from '../../api/admin'
import { createOrder } from '../../api/user'
import { getDoctorSchedules } from '../../api/doctor'
import { useAuthStore } from '../../store/auth'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const auth = useAuthStore()
const list = ref([])
const total = ref(0)
const query = ref({ code: '', name: '', categoryId: '', page: 1, size: 10 })
const loading = ref(false)
const reserveDialog = ref(false)
const reserveForm = ref({ doctorId: null, orderDate: '' })
const currentIndicator = ref(null)
const doctorList = ref([])
const successDialog = ref(false)
const successOrder = ref(null)
const router = useRouter()
// 订单状态标签（整数）
const orderStatusLabel = (s) => ({ 1: '待确认', 2: '已确认', 3: '已完成', 4: '已取消' }[s] || s)

const disablePastDates = (date) => {
  const today = new Date()
  today.setHours(0,0,0,0)
  return date.getTime() < today.getTime()
}

const fetchList = async () => {
  loading.value = true
  try {
    const data = await listIndicators({ code: query.value.code || undefined, name: query.value.name || undefined, categoryId: query.value.categoryId || undefined, page: query.value.page, size: query.value.size })
    list.value = data.list || []
    total.value = data.total || 0
  } finally { loading.value = false }
}

const reserve = (row) => {
  currentIndicator.value = row
  reserveForm.value = { doctorId: null, orderDate: '' }
  reserveDialog.value = true
}

const submitReserve = async () => {
  if (!auth.currentId) { ElMessage.error('请先登录用户账号'); return }
  if (!currentIndicator.value) { ElMessage.error('未选择项目'); return }
  if (!reserveForm.value.doctorId || !reserveForm.value.orderDate) { ElMessage.warning('请选择医生和日期'); return }
  // 校验医生排班
  try {
    const sched = await getDoctorSchedules(reserveForm.value.doctorId, { date: reserveForm.value.orderDate, page: 1, size: 5 })
    if (!sched || (sched.list || []).length === 0) {
      ElMessage.error('该医生在所选日期无排班，请更换日期或医生')
      return
    }
  } catch (e) {
    ElMessage.warning('未能验证医生排班，继续提交预约')
  }
  loading.value = true
  try {
    const order = await createOrder(auth.currentId, {
      doctorId: reserveForm.value.doctorId,
      orderDate: reserveForm.value.orderDate,
      orderType: 'INDICATOR',
      indicatorId: currentIndicator.value.indicatorId,
      remark: ''
    })
    ElMessage.success('预约成功')
    successOrder.value = order
    successDialog.value = true
    reserveDialog.value = false
    reserveForm.value = { doctorId: null, orderDate: '' }
  } finally { loading.value = false }
}

onMounted(async () => {
  try {
    const [docsRes] = await Promise.allSettled([
      listDoctors({ page: 1, size: 200 })
    ])
    if (docsRes.status === 'fulfilled') {
      doctorList.value = docsRes.value.list || []
    }
  } catch (e) { /* ignore mapping errors */ }
  await fetchList()
})
</script>

<template>
  <el-card>
    <h3>体检项目列表</h3>
    <el-form :inline="true" :model="query" class="mb-2">
      <el-form-item label="代码"><el-input v-model="query.code" placeholder="指标代码" /></el-form-item>
      <el-form-item label="名称"><el-input v-model="query.name" placeholder="指标名称" /></el-form-item>
      <el-form-item label="类别ID"><el-input v-model="query.categoryId" placeholder="类别ID" /></el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query.page=1;fetchList()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="list" v-loading="loading" style="width:100%">
      <el-table-column prop="indicatorId" label="ID" width="80" />
      <el-table-column prop="indicatorCode" label="代码" />
      <el-table-column prop="indicatorName" label="名称" />
      <el-table-column prop="categoryId" label="类别ID" />
      <el-table-column label="操作" width="140">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="reserve(row)">预约</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="mt-2">
      <el-pagination background layout="total, prev, pager, next" :total="total" :page-size="query.size" :current-page="query.page" @current-change="(p)=>{query.page=p;fetchList()}" />
    </div>
  </el-card>

  <el-dialog v-model="reserveDialog" :title="currentIndicator?.indicatorName ? '预约体检 - '+currentIndicator.indicatorName : '预约体检'" width="480px">
    <el-form label-width="90px">
      <el-form-item label="选择医生">
        <el-select v-model="reserveForm.doctorId" placeholder="选择医生" style="width:240px">
          <el-option v-for="d in doctorList" :key="d.doctorId" :label="d.name" :value="d.doctorId" />
        </el-select>
      </el-form-item>
      <el-form-item label="体检日期">
        <el-date-picker v-model="reserveForm.orderDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" style="width:240px" :disabled-date="disablePastDates" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="reserveDialog=false">取消</el-button>
      <el-button type="primary" :loading="loading" @click="submitReserve">确定预约</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="successDialog" title="预约成功" width="520px">
    <el-descriptions :column="1" border>
      <el-descriptions-item label="订单号">{{ successOrder?.orderId || '-' }}</el-descriptions-item>
      <el-descriptions-item label="体检项目">{{ currentIndicator?.indicatorName || '-' }}</el-descriptions-item>
      <el-descriptions-item label="主检医生">{{ (doctorList.find(d=>d.doctorId===successOrder?.doctorId) || {}).name || '-' }}</el-descriptions-item>
      <el-descriptions-item label="体检日期">{{ successOrder?.orderDate || '-' }}</el-descriptions-item>
      <el-descriptions-item label="状态">{{ orderStatusLabel(successOrder?.status) }}</el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <el-button @click="successDialog=false">继续浏览</el-button>
      <el-button type="primary" @click="successDialog=false; router.push('/user/orders')">去我的订单</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.mb-2{ margin-bottom:12px; }
.mt-2{ margin-top:12px; }
</style>